<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>待办详情</title>
    <meta name="viewport"
      content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../../../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet" />
    <style>
      .mui-pull-bottom-tips {
        text-align: center;
      }

      .mui-card {
        border-radius: 5px;
        box-shadow: none;
        padding: 20px;
        color: #333333;
      }

      .mui-card-header {
        padding: 0 0 20px 0;
        position: relative;
        font-size: 16px;
      }

      .no_work_ticket {
        text-align: center;
        border-bottom: 1px dotted #c2cfda;
        padding-bottom: 15px;
      }

      .no_img,
      .mui-slider .mui-slider-group .mui-slider-item img {
        width: 20%;
      }

      .work_ticket_time {
        text-align: center;
        font-size: 14px;
        line-height: 30px;
        padding: 15px;
        border-bottom: 1px dotted #c2cfda;
      }

      .red {
        color: #f35b5b;
      }

      .buld {
        color: #3188fe;
      }

      .no_work_ticket span {
        font-size: 20px;
        font-weight: 600;
        color: #999999;
      }

      .task-info ul {
        margin: 0;
        padding: 0;
      }

      .task-info ul li {
        list-style: none;
        line-height: 30px;
        font-size: 15px;
        display: flex;
        justify-content: space-between;
      }

      .task-info ul li span:nth-child(1) {
        color: #a2a8ae;
        width: 120px;
      }

      .task-info ul li span:nth-child(2) {
        color: #333333;
      }

      .f14 {
        font-weight: bold;
        font-size: 16px;
        line-height: 50px;
      }

      .flex,
      .flex2 {
        border-top: 1px solid #c2cfda;
        line-height: 50px;
        display: flex;
        justify-content: space-between;
      }

      .flex span:nth-child(1) {
        font-weight: bold;
      }

      .flex span:nth-child(2) {
        color: #3188fe;
      }

      .flex span:nth-child(2):after {
        font-size: 15px;
        right: 15px;
        content: '\e583';
        font-family: Muiicons;
        color: #bbb;
      }

      .flex2 span:nth-child(1) {
        padding-left: 10px;
      }

      .step {
        padding-bottom: 15px;
      }

      .step button {
        margin: 4px;
        width: 33px;
        height: 33px;
        text-align: center;
        padding: 0;
      }

      .sub {
        position: fixed;
        z-index: 1;
        border-top: 1px solid #dfdfdf;
        width: 100%;
        bottom: 0;
        background: #fff;
      }

      .sub div {
        margin: 10px;
        line-height: 40px;
        background: #3188fe;
        border-radius: 20px;
        text-align: center;
        color: #fff;
      }

      .gary {
        color: #999999;
      }

      .tips {
        text-align: center;
        font-weight: bold;
        line-height: 40px;
        font-size: 18px;
        border-bottom: 1px solid #dcdcdc;
      }

      .option {
        display: flex;
        justify-content: space-around;
        margin-top: 20px;
      }

      .option button {
        width: 80px;
      }

      .option.justify-center {
        justify-content: center;
      }

      .tips-list {
        margin-top: 30%;
      }

      .mui-btn-gary {
        color: #fff;
        border: 1px solid #cccc;
        background-color: #cccc;
      }
	  .tips-lx{position: absolute;right: 0;top: 0;background: #dfdfdf; padding: 5px;border-radius: 5px;}
    </style>
  </head>

  <body>
    <div id="container" v-cloak>
      <header class="mui-bar mui-bar-nav">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title">执行待办</h1>
      </header>
      <div class="mui-content app-container">
        <div style="padding-bottom: 60px">
          <div class="mui-card card_content" style="position: relative;">
			<span class="tips-lx" v-if="islx">当前是离线数据</span>
            <div v-if="projectList.workTicket">
              <div v-if="projectList.workTicket.status == 0" class="no_work_ticket">
                <img src="../img/no_work_ticket.png" class="no_img" />
                <br />
                <span>工作票未开</span>
              </div>
              <!-- 缺少工作票未开状态，工作票是否超时状态 -->

              <!-- 工作票时间未超时显示蓝色，已超时显示红色 -->
              <div v-else :class="['work_ticket_time', projectList.isOver? 'red': 'buld']">
                工作票时间
                <br />
                {{projectList.workTicket.startTime}} - {{projectList.workTicket.endTime}}
              </div>
            </div>

            <div>
              <span class="f14">任务信息</span>
              <div class="task-info">
                <ul v-if="projectList.taskInfo">
                  <li>
                    <span>设备：</span>
                    <span>{{projectList.taskInfo.deviceModelName}}</span>
                  </li>
                  <li>
                    <span>规格/型号：</span>
                    <span>{{projectList.taskInfo.model}}</span>
                  </li>
                  <li>
                    <span>位置编码：</span>
                    <span>{{projectList.taskInfo.locationCode}}</span>
                  </li>
                  <li>
                    <span>检修任务：</span>
                    <span>{{projectList.taskInfo.name}}</span>
                  </li>
                  <li>
                    <span>计划开始时间：</span>
                    <span>{{formatDate(projectList.taskInfo.starttime, 'yyyy-MM-dd hh:mm')}}</span>
                  </li>
                  <li>
                    <span>计划结束时间：</span>
                    <span>{{formatDate(projectList.taskInfo.endtime, 'yyyy-MM-dd hh:mm')}}</span>
                  </li>
                </ul>
              </div>
              <div class="flex" @tap="toToolList()">
                <span>工器具清单</span>
                <span>查看</span>
              </div>
              <div class="flex" @tap="toDeviceList()">
                <span>该设备是关键敏感设备，有以下风险描述</span>
                <span>查看</span>
              </div>
              <div class="step">
                <!-- <div v-for="(list,index) in projectList.sensitiveList" :key="index">
                  <div>{{index}}</div>
                  <button type="button" v-for="(item,index) in list" class="mui-btn" :class="sensitiveStatus(item.status)" @click="toImplement(item)">{{index+1}}</button>
                </div> -->
                <div v-for="(a,index) in projectList.sensitiveList" :key="index">
                  <span v-if="a.taskWps.length > 0">{{a.deviceName}}</span>
                  <div><button type="button" class="mui-btn" v-for="(item_a,index) in a.taskWps"
                      :class="sensitiveStatus(item_a.status)" @click="toImplement(item_a)">{{index+1}}</button></div>

                  <div v-for="(b,index) in a.childs" :key="index">
                    <span v-if="b.taskWps.length > 0">{{b.parentName}}/{{b.deviceName}}</span>
                    <div><button type="button" class="mui-btn" v-for="(item_b,index) in b.taskWps"
                        :class="sensitiveStatus(item_b.status)" @click="toImplement(item_b)">{{index+1}}</button></div>
                    <div v-for="(c,index) in b.childs" :key="index">
                      <span v-if="c.taskWps.length > 0">{{c.parentName}}/{{c.deviceName}}</span>
                      <div><button type="button" class="mui-btn" v-for="(item_c,index) in c.taskWps"
                          :class="sensitiveStatus(item_c.status)" @click="toImplement(item_c)">{{index+1}}</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex" @tap="toCompleteList()">
                <span>工序完成情况（共{{ countWp }}个工序）</span>
                <span>查看</span>
              </div>
              <div class="step">
                <div v-for="(a,index) in projectList.wpItemList" :key="index">
                  <span v-if="a.taskWps.length > 0">{{a.deviceName}}</span>
                  <div><button type="button" class="mui-btn" v-for="(item_a,index) in a.taskWps"
                      :class="wpItemStatus(item_a)" @click="toDetail(item_a)">{{tagBackText(item_a,index)}}</button>
                  </div>

                  <div v-for="(b,index) in a.childs" :key="index">
                    <span v-if="b.taskWps.length > 0">{{b.parentName}}/{{b.deviceName}}</span>
                    <div><button type="button" class="mui-btn" v-for="(item_b,index) in b.taskWps"
                        :class="wpItemStatus(item_b)" @click="toDetail(item_b)">{{tagBackText(item_b,index)}}</button>
                    </div>
                    <div v-for="(c,index) in b.childs" :key="index">
                      <span v-if="c.taskWps.length > 0">{{c.parentName}}/{{c.deviceName}}</span>
                      <div><button type="button" class="mui-btn" v-for="(item_c,index) in c.taskWps"
                          :class="wpItemStatus(item_c)" @click="toDetail(item_c)">{{tagBackText(item_c,index)}}</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="sub">
        <div id="allSub" @tap="allSub(true)">全部完成提交</div>
      </div>

      <!-- tips -->
      <div class="mui-backdrop" v-show="isMask">
        <div class="tips-list">
          <div class="mui-card card_content">
            <div class="tips">工作提醒</div>
            <div class="flex" @tap="tipsDetail('reminders');read1=true">
              <span>工作提醒</span>
              <span v-if="read1">已阅读</span>
              <span v-else style="color: #999999">未阅读</span>
            </div>
            <div class="flex" @tap="tipsDetail('instruction');read2=true">
              <span>操作须知</span>
              <span v-if="read2">已阅读</span>
              <span v-else style="color: #999999">未阅读</span>
            </div>
            <div class="option justify-center">
              <button type="button" class="mui-btn" @click="closeLayer(1)">关闭</button>
              <!--<button type="button" class="mui-btn mui-btn-primary">确定</button>-->
            </div>
          </div>
        </div>
      </div>

      <!-- 未完成工序提示 -->
      <div class="mui-backdrop" v-show="isIncomplete">
        <div class="tips-list">
          <div class="mui-card card_content">
            <div class="tips">您有{{this.arr.length}}个工序未填写请选择原因</div>
            <div style="height: 400px; overflow-y: auto">
              <div class="flex2" v-for="(obj,index) in arr" :key="index" v-cloak>
                <span>{{obj.id}}</span>
                <span v-for="(item,v) in obj.list">
                  <label :for="v">
                    <input type="checkbox" :id="v" :key="index+'_'+v" v-model="item.state"
                      style="vertical-align: middle" />
                    {{item.text}}
                  </label>
                </span>
              </div>
            </div>
            <div class="option">
              <button type="button" class="mui-btn" @tap="closeLayer(2)">继续执行</button>
              <button type="button" class="mui-btn mui-btn-primary" @tap="unfinishedSub()">提交</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="../../../js/mui.js"></script>
    <script src="../../../js/vue.js"></script>
    <script src="../js/mkeyplus.base.js"></script>
    <script src="../js/indexDBs.js"></script>
    <script type="text/javascript">
      mui.init()
      var size = 15;
      var page = 1;
      var donePage = 1;
      let taskId = null;
      let self = null;
      let lineType =null;
      let db={};
      const dbName = 'myDBs'; // 数据库的名字
      const storeName = 'listPackage'; //仓库名称
      mui.plusReady(async function() {
        self = plus.webview.currentWebview();
        taskId = self.taskId;
        vm.lineType= getSysInfo();
        lineType = getSysInfo();
        // 打开数据库
        await openDB(dbName, storeName, 1).then(res=>{
           console.log('openDB',res)
           db = res
        })
        // 是否离线
		if(!lineType){
			getLocalOfflineData(taskId)
			vm.islx = true
		} else {
			// 有网有离线数据
			getDataByKey(db, storeName,taskId).then(res=>{
				console.log('是否有离线数据',res)
				if(res == undefined){
					getProject()
					vm.unexecutedReason()
					vm.isOnlineAndOfflineData = false
				} else {
					getLineData()
					vm.unexecutedReason()
					// vm.lineType = lineType = false
					vm.isOnlineAndOfflineData = true
					vm.islx = true
				}
			})
		}
         
      })

      var vm = new Vue({
        el: '#container',
        data: {
		  isOnlineAndOfflineData: false,
		  islx: false,
          isMask: true,
          isIncomplete: false,
          projectList: {},
          tipsInfo: {},
          arr: [],
          reason: [],
          isSub: true,
          read1: false,
          read2: false,
          isTrue:false,
          countWp: '',
          lineType:null,
          wpReturn:[], //退回工序
          wpList:[],//基本工序
          subWpList:[] ,//辅助工序
          sensitiveList:[],
          subSensitiveList:[]
        },
        created: function() {
          // this.getTipsInfo()
        },
        methods: {
          formatDate(tmp, fmt) {
            return mui.baseApp.formatDate(tmp, fmt)
          },
          toToolList() {
            let id = taskId
            mui.baseApp.openWindow('./carryoutToolList.html',{
              workId: id,
            })
          },
          toDeviceList() {
            let id = taskId
            mui.baseApp.openWindow('./riskList.html', {
              workId: id
            })
          },
          toCompleteList() {
            let id = taskId
            mui.baseApp.openWindow('./workingList.html', {
              workId: id
            })
          },
          toDetail(item) {
            let arr = []
            let i = 0
            let currentIndex = 0 // 当前点击工序索引
            vm.projectList.wpItemList.forEach((a, i) => {
              arr = arr.concat(a.taskWps)
              a.childs.forEach((b, index) => {
                arr = arr.concat(b.taskWps)
                b.childs.forEach((c, index) => {
                  arr = arr.concat(c.taskWps)
                })
              })
            })
            arr.forEach((wp, index) => {
              wp.index = index
              if (wp.id == item.id) {
                currentIndex = wp.index
              }
            })
            mui.baseApp.openWindow('./workingCode.html', {
              projectTaskId: item.id,
              tagId: item.tagId,
              idxs: currentIndex,
              aList: arr,
              dbId: taskId
            })
          },
          toImplement(item) {
            let arr = []
            let currentIndex = 0 // 当前点击工序索引
            vm.projectList.sensitiveList.forEach((a, i) => {
              arr = arr.concat(a.taskWps)
              a.childs.forEach((b, index) => {
                arr = arr.concat(b.taskWps)
                b.childs.forEach((c, index) => {
                  arr = arr.concat(c.taskWps)
                })
              })
            })
            arr.forEach((wp, index) => {
              wp.index = index
              if (wp.id == item.id) {
                currentIndex = wp.index
              }
            })
            mui.baseApp.openWindow('./implement.html', {
              projectTaskId: item.id,
			        tagId: item.tagId,
              idxs: currentIndex,
              aList: arr,
              dbId:taskId
            })
          },
          closeLayer(val) {
            if (val == 1) {
              this.isMask = false
            } else {
              this.isIncomplete = false
            }
          },
          tipsDetail(type) {
            mui.baseApp.openWindow('./carryoutTipsDetail.html?type='+type)
          },
          getTipsInfo() {
            mui.baseApp.httpRequst(
              'get',
              '/app/api/project/execution/tips', {},
              (data) => {
                console.log(data)
                this.tipsInfo = data.data
              },
              () => {
                console.log('获取数据失败')
              }
            )
          },
          sensitiveStatus(status) {
            // 0:未开始 1: 进行中 2:已完成
            if (status == 0) {
              return ''
            }
            if (status == 1) {
              return 'mui-btn-success'
            }
            if (status == 4) {
              return 'mui-btn-primary'
            }
          },
          wpItemStatus(item) {
            // 蓝色为正常执行，白色为未执行，红色为异常执行，灰色为退回，黄色为缺陷
            // 状态 0:未开始 1: 进行中 2:整改中 3:已完成 4: 验收
            if (item.isAnomaly == true) {
              return 'mui-btn-danger'
            } // 是否异常
            if (item.isFault == true) {
              return 'mui-btn-warning'
            } // 是否缺陷
            if (item.status == 3) {
              return 'mui-btn-gary'
            } // 是否回退
            if (item.isRectify == true) {
              return ''
            } // 是否待整改
            if (item.isPass == true) {
              return 'mui-btn-primary'
            } // 是否通过
            if (item.status == 4 || item.status == 2) {
              return 'mui-btn-primary'
            } // 已完成
          },
          tagBackText(item, index) {
            // 待271 现272 旁273
            if (item.tagId == 271) {
              return '待'
            } else if (item.tagId == 272) {
              return '现'
            } else if (item.tagId == 273) {
              return '旁'
            } else {
              return index + 1
            }
          },
          unfinishedSub() {
            // 验证工序未完成是否选择原因
            let isFill = true
            console.log('数组没完成工序',JSON.stringify(this.arr))
            this.arr.forEach((item) => {
              if (item.list.length>0 && item.list[0].state == false && item.list[1].state == false) {
                isFill = false
              }
            })
			// const allFalse = this.arr.every((item) =>
			//   item.list.every((obj) => obj.state === false)
			// );
            isFill ? this.uncheckSubmit(this.isTrue) : mui.toast('请选择每个工序未完成原因')
          },
          unexecutedReason() {
            let _this = this
            mui.baseApp.httpRequst(
              'post',
              '/app/sys/dictItem/getDictDetail', {
                dictName: 'wpUnexecutedReason'
              },
              function(data) {
                console.log('原因', data.data)
                data.data.forEach((item) => {
                  _this.reason.push({
                    text: item.label,
                    state: false
                  })
                })
              },
              function() {
                console.log('获取数据失败')
              }
            )
          },
         async allSub(isSubs) {
			console.log('离线数据',this.isOnlineAndOfflineData)
           let then = this
            if(!lineType){
              // mui.toast('请检查网络是否连接！')
              mui.confirm('请检查网络！是否需要保存离线编辑内容？','提示',['是','否'],function(item){
                console.log('对话框提示',item)
                if(item.index==0){
                  getLineData()
                }else{
                  getDel(taskId)
                }
              })
              return
            } else {
             getDataByKey(db, storeName,taskId).then(res=>{
               let count = 0
               let isReturn=0
               console.log('qqq',JSON.stringify(res))
               res&&res.wpItemList&&res.wpItemList.forEach((a, i) => {
                 a.taskWps.forEach(item => {
                   if (item.status==4) {
                     count++
                   }
                   if(item.isReturn){
                     isReturn++
                   }
                    
                 })
                 a.childs.forEach((b, index) => {
                   b.taskWps.forEach(item => {
                     if (item.status==4) {
                       count++
                     }
                     if(item.isReturn){
                       isReturn++
                     } 
                   })
                   b.childs.forEach((c, index) => {
                     c.taskWps.forEach(item => {
                       if (item.status==4) {
                         count++
                       }
                       if(item.isReturn){
                         isReturn++
                       }
                     })
                   })
                 })
               })
               res&&res.sensitiveList&&res.sensitiveList.forEach((a, i) => {
                 a.taskWps.forEach(item => {
                   if (item.status==4) {
                     count++
                   }
                    
                 })
                 a.childs.forEach((b, index) => {
                   b.taskWps.forEach(item => {
                     if (item.status==4) {
                       count++
                     }
                      
                   })
                   b.childs.forEach((c, index) => {
                     c.taskWps.forEach(item => {
                       if (item.status==4) {
                         count++
                       }
                     })
                   })
                 })
               })
                 if(res&&res.id==taskId&&(count>0||isReturn>0)){
                   mui.confirm('当前是离线数据，是否需要保存并提交？','提示',['是','否'],async function(item){
                     console.log('对话框提示',item)
                     if(item.index==0){
                        then.isTrue=true
                        // await getLineData()
                        await then.allSubs(true)
                     }
                   })
                 }else{
                   getDel(taskId)
                   if(isSubs){
                     then.allSubs(false)
                   }
                 }

               })
            }
          },
         allSubs(isTrue){
           this.arr = []
           this.wpReturn=[]
           this.wpList=[]
           this.subWpList=[]
           console.log('tijao111111',JSON.stringify(vm.projectList.wpItemList))
           Object.values(vm.projectList.wpItemList).forEach((a) => {
             a.taskWps.forEach((task) => {
               if (task.status == 0 || task.status == 1) {
                 const tmp = this.reason.map((item) => {
                   return {
                     ...item
                   }
                 })
                 this.arr.push({
                   id: task.id,
                   list: tmp
                 })
               }
               if(task.isReturn){
                 this.wpReturn.push(task.id)
               }
               if(task.details){
                 if(task.status==4){
                   // delete task.details.subWps
                   this.wpList.push(task.details)
                 }
                 if(task.details.subWps&&task.details.subWps.length>0){
                   // this.subWpList.concat(task.details.subWps)
                   task.details.subWps.forEach(item=>{
                     if(item.status==4){
                       this.subWpList.push(item)
                     }
                   })
                 }
               }
                
             })
             a.childs.forEach((item) => {
               console.log(22, item)
               // 判断第2层
               if (item.taskWps.length > 0) {
                 item.taskWps.forEach((task) => {
                   if (task.status == 0 || task.status == 1) {
                     const tmp = this.reason.map((item) => {
                       return {
                         ...item
                       }
                     })
                     this.arr.push({
                       id: task.id,
                       list: tmp
                     })
                   }
                   if(task.isReturn){
                     this.wpReturn.push(task.id)
                   }
                   if(task.details){
					   console.log(1111,task.details)
                     if(task.status==4){
                       this.wpList.push(task.details)
                     }
                     if(task.details.subWps&&task.details.subWps.length>0){
                       // this.subWpList.concat(task.details.subWps)
                       task.details.subWps.forEach(item=>{
                         if(item.status==4){
                         this.subWpList.push(item)
                         }
                       })
                     }
                   }
                    
                 })
               }
           
               item.childs.forEach((a) => {
                 if (a.taskWps.length > 0) {
                   a.taskWps.forEach((b) => {
                     if (b.status == 0 || b.status == 1) {
                       const tmp = this.reason.map((a) => {
                         return {
                           ...a
                         }
                       })
                       this.arr.push({
                         id: b.id,
                         list: tmp
                       })
                     }
                     if(b.isReturn){
                       this.wpReturn.push(b.id)
                     }
                     if(b.details){
                       if(b.status==4){
                         this.wpList.push(b.details)
                       }
                       if(b.details.subWps&&b.details.subWps.length>0){
                         // this.subWpList.concat(b.details.subWps)
                         b.details.subWps.forEach(item=>{
                           if(item.status==4){
                           this.subWpList.push(item)
                           }
                         })
                       }
                     }
                      
                   })
                 }
               })
           
             })
           })
           this.sensitiveList=[]
           this.subSensitiveList=[]
           Object.values(vm.projectList.sensitiveList).forEach((a) => {
             a.taskWps.forEach((task) => {
               if(task.details){
                 if(task.status==4){
                   // delete task.details.subWps
                   this.sensitiveList.push(task.details)
                 }
                 if(task.details.subWps&&task.details.subWps.length>0){
                   // this.subWpList.concat(task.details.subWps)
                   task.details.subWps.forEach(item=>{
                     if(item.status==4){
                     this.subSensitiveList.push(item)
                     }
                   })
                 }
               }
                
             })
             a.childs.forEach((item) => {
               console.log(22, item)
               // 判断第2层
               if (item.taskWps.length > 0) {
                 item.taskWps.forEach((task) => {
                   if(task.details){
                     if(task.status==4){
                       this.sensitiveList.push(task.details)
                     }
                     if(task.details.subWps&&task.details.subWps.length>0){
                       // this.subWpList.concat(task.details.subWps)
                       task.details.subWps.forEach(item=>{
                         if(item.status==4){
                         this.subSensitiveList.push(item)
                         }
                       })
                     }
                   }
                    
                 })
               }
           
               item.childs.forEach((a) => {
                 if (a.taskWps.length > 0) {
                   a.taskWps.forEach((b) => {
                     if(b.details){
                       if(b.status==4){
                         this.sensitiveList.push(b.details)
                       }
                       if(b.details.subWps&&b.details.subWps.length>0){
                         // this.subWpList.concat(b.details.subWps)
                         b.details.subWps.forEach(item=>{
                           if(item.status==4){
                           this.subSensitiveList.push(item)
                           }
                         })
                       }
                     }
                      
                   })
                 }
               })
           
             })
           })
           console.log('未完成工序', this.arr)
           if (this.arr.length > 0) {
             this.isSub = false
             this.isIncomplete = true
             return
           }
           if (this.isSub == true) {
             this.uncheckSubmit(isTrue)
           }
         },
         async uncheckSubmit(isTrue) {
            if(isTrue){
              this.lineSubmit()
              return
            }
            let params = {
              stage: '3',
              reasons: this.arr,
              projectTaskId: taskId
            }
			plus.nativeUI.showWaiting('提交中...');
            mui.baseApp.httpRequst(
              'post',
              '/app/api/project/execution/uncheckSubmit',
              params,
              (data) => {
                console.log(data)
                if (data.code == 0) {
					plus.nativeUI.closeWaiting();
					this.arr = []
					mui.toast('提交成功')
					getDel(taskId)
					mui.fire(self.opener(), 'back', {})
					mui.back()
                }
              },
              () => {
                console.log('提交失败')
              }
            )
          },
          // anomalyInfo.files // faultInfo.files           
          async upLoadtest(arr) {
            // console.log('图片6666',JSON.stringify(arr))
			console.log('图片',arr)
            if(arr.length>0){
              for (let i=0;i<arr.length;i++) {
                // refInput 文件类型 
                if(arr[i]&&arr[i].inputs&&arr[i].inputs.length>0){
                  let items=arr[i].inputs
                  console.log('aaaaaaaaaa',JSON.stringify(items))
                   for(let j=0;j<items.length;j++){
                     let inputs=items[j]
                     console.log('ddddddddddd',JSON.stringify(inputs))
                     if(inputs&&inputs.files&&inputs.files.length>0){
                       // let psths=inputs
                       for(let v=0; v < inputs.files.length; v++){
                         if(inputs.files[v].filePath){
                           let isStr = inputs.files[v].filePath.indexOf('file:')
                           if(isStr!=-1){
                             let lists=await new Promise((resolve, reject)=>{
                                   mui.baseApp.upLoadFile(inputs.files[v].filePath,function(res) {
                                   console.log('返回数据',JSON.stringify(res))
                                   // plus.nativeUI.closeWaiting()
                                   resolve(res)
                                 }) 
                              })
                              let objs={
                                   fileId: lists.data.id,
                                   filePath: lists.data.fileDirectory
                                 }
                               console.log('lis列表aaaa',JSON.stringify(lists))
                               // console.log('lis列表aaaa',JSON.stringify(fileList))
                               this.$set(inputs.files,v,objs)
                           }
                            
                         }
                          
                       }
                     }
                   }
                }
                // 是否正常
                if(arr[i]&&arr[i].anomalyInfo&&arr[i].anomalyInfo.files.length>0){
                   let items=arr[i].anomalyInfo.files
                       for(let j=0;j<items.length;j++){
                          
                         if(items[j]&&items[j].filePath){
                           let isStr = items[j].filePath.indexOf('file:')
                           if(isStr!=-1){
                             console.log('是否正常66669999',JSON.stringify(items[j].filePath))
                             let lists=await new Promise((resolve, reject)=>{
                                   mui.baseApp.upLoadFile(items[j].filePath,function(res) {
                                   console.log('返回数据',JSON.stringify(res))
                                   // plus.nativeUI.closeWaiting()
                                   resolve(res)
                                 }) 
                              })
                              let objs={
                                   fileId: lists.data.id,
                                   filePath: lists.data.fileDirectory
                                 }
                               console.log('lis列表aaaa',JSON.stringify(lists))
                               // console.log('lis列表aaaa',JSON.stringify(fileList))
                               this.$set(items,j,objs)
                           }
                         }
                       }
                       console.log('lis列表bbbbbb',JSON.stringify(items))
                   }
                   // 生成缺陷
                   if(arr[i]&&arr[i].faultInfo&&arr[i].faultInfo.files.length>0){
                      let items=arr[i].faultInfo.files
                          for(let j=0;j<items.length;j++){
                             
                            if(items[j]&&items[j].filePath){
                              let isStr = items[j].filePath.indexOf('file:')
                              if(isStr!=-1){
                                console.log('图片66669999',JSON.stringify(items[j].filePath))
                                let lists=await new Promise((resolve, reject)=>{
                                      mui.baseApp.upLoadFile(items[j].filePath,function(res) {
                                      console.log('返回数据',JSON.stringify(res))
                                      // plus.nativeUI.closeWaiting()
                                      resolve(res)
                                    }) 
                                 })
                                 let objs={
                                      fileId: lists.data.id,
                                      filePath: lists.data.fileDirectory
                                    }
                                  console.log('lis列表aaaa',JSON.stringify(lists))
                                  // console.log('lis列表aaaa',JSON.stringify(fileList))
                                  this.$set(items,j,objs)
                              }
                               // let fileList=[]
                            }
                          }
                          console.log('lis列表bbbbbb',JSON.stringify(items))
                      }
                      // 负责人signInfo
                      if(arr[i]&&arr[i].signInfo&&arr[i].signInfo.takeImg&&arr[i].signInfo.takeImg.filePath){
                        let isStra = arr[i].signInfo.takeImg.filePath.indexOf('file:')
                        if(isStra!=-1){
                          let lists=await new Promise((resolve, reject)=>{
                                mui.baseApp.upLoadFile(arr[i].signInfo.takeImg.filePath,function(res) {
                                console.log('返回数据',JSON.stringify(res))
                                // plus.nativeUI.closeWaiting()
                                resolve(res)
                              }) 
                           })
                           let objs={
                                fileId: lists.data.id,
                                filePath: lists.data.fileDirectory
                              }
                            console.log('lis列表aaaa',JSON.stringify(lists))
                            // console.log('lis列表aaaa',JSON.stringify(fileList))
                            this.$set(arr[i].signInfo.takeImg,'filePath',objs.filePath)
                            this.$set(arr[i].signInfo.takeImg,'fileId',objs.fileId)
                        }
                         
                      }
                      // 签字signImg
                       
                      if(arr[i]&&arr[i].signInfo&&arr[i].signInfo.signImg&&arr[i].signInfo.signImg.filePath){
                        let isStrs = arr[i].signInfo.signImg.filePath.indexOf('file:')
                        if(isStrs!=-1){
                           let lists=await new Promise((resolve, reject)=>{
                                 mui.baseApp.upLoadFile(arr[i].signInfo.signImg.filePath,function(res) {
                                 console.log('返回数据',JSON.stringify(res))
                                 // plus.nativeUI.closeWaiting()
                                 resolve(res)
                               }) 
                            })
                            let objs={
                                 fileId: lists.data.id,
                                 filePath: lists.data.fileDirectory
                               }
                             console.log('lis列表aaaa',JSON.stringify(lists))
                             // console.log('lis列表aaaa',JSON.stringify(fileList))
                             this.$set(arr[i].signInfo.signImg,'filePath',objs.filePath)
                             this.$set(arr[i].signInfo.signImg,'fileId',objs.fileId)
                        }
                      }
                }
                 
                 
            }
             
            return arr
          },
         async lineSubmit(){
           let wpList=await this.upLoadtest(this.wpList)
           let subWpList =await this.upLoadtest(this.subWpList)
           let sensitiveList=await this.upLoadtest(this.sensitiveList)
           let subSensitiveList = await this.upLoadtest(this.subSensitiveList)
            // console.log('图片1111111',JSON.stringify(wpList))
			console.log('离线图片',wpList)
            let params = {
              stage: '3',
              reasons: this.arr,
              projectTaskId: taskId,
              sensitiveList: sensitiveList,
              wpList: wpList, //已执行基本工序
              subSensitiveList: subSensitiveList,
              subWpList: subWpList, //已执行辅助工序
              wpReturnList: this.wpReturn,
            }
            console.log('离线全部提交',JSON.stringify(params),params)
            //return
			      plus.nativeUI.showWaiting('提交中...');
            mui.baseApp.httpRequst(
              'post',
              '/app/api/project/execution/offline/data',
              params,
              (data) => {
                console.log(data)
                if (data.code == 0) {
				          plus.nativeUI.closeWaiting();
                  this.arr = []
                  mui.toast('提交成功')
                  // mui.fire(self.opener(), 'back', {})
                  // mui.back()
                }
              },
              () => {
                console.log('提交失败')
              }
            )
          },
          uploadImg(path){
            mui.baseApp.upLoadFile(path, function(res) {
              console.log(res)
              // plus.nativeUI.closeWaiting()
               return {
                  fileId: res.data.id,
                  filePath: res.data.fileDirectory
                }
            })
          }
        }
      })

      function getUrlParams(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        var r = window.location.search.substr(1).match(reg)
        if (r != null) return unescape(r[2])
        return null
      }
	  
	  function getLocalOfflineData(taskId){
		cursorGetData(db, storeName).then(res=>{
			console.log('all Data',res)
			res.forEach((item,index) => {
				if(item.id == taskId){
					item.isOver = false
					if(item.workTicket && item.workTicket.endTime && new Date().getTime() > new Date(item.workTicket.endTime).getTime()) {
					  item.isOver = true //工作票超时
					}
					vm.projectList = item
					console.log('缓存工序', Object.values(vm.projectList.wpItemList))
					// 统计工序个数
					let arr = []
					Object.values(vm.projectList.wpItemList).forEach((a, i) => {
					  arr.push(a.taskWps.length)
					  a.childs.forEach((b, index) => {
					    arr.push(b.taskWps.length)
					    b.childs.forEach((c, index) => {
					      arr.push(c.taskWps.length)
					    })
					  })
					})
					vm.countWp = arr.reduce((x, y) => x + y)
				}
			})
		}).catch(function (error) {
		 console.log(error);
		})
	  }

      function getProject() {
        plus.nativeUI.showWaiting('加载中')
        let id = taskId
        mui.baseApp.httpRequst(
          'get',
          '/app/api/project/execution/detail/' + id, {},
          function(data) {
            plus.nativeUI.closeWaiting()
            console.log('详情数据',data)
            data.data.isOver = false
            if(data.data.workTicket && data.data.workTicket.endTime && new Date().getTime() > new Date(data.data.workTicket.endTime).getTime()) {
              data.data.isOver = true //工作票超时
            }
            
            vm.projectList = data.data

            console.log(111, Object.values(vm.projectList.wpItemList))
            // 统计工序个数
            let arr = []
            Object.values(vm.projectList.wpItemList).forEach((a, i) => {
              arr.push(a.taskWps.length)
              a.childs.forEach((b, index) => {
                arr.push(b.taskWps.length)
                b.childs.forEach((c, index) => {
                  arr.push(c.taskWps.length)
                })
              })
            })
            vm.countWp = arr.reduce((x, y) => x + y)
          },
          function() {
            plus.nativeUI.closeWaiting()
            console.log('获取数据失败')
          }
        )
      }
      // 获取离线数据
     async function getLineData(){
      await getDataByKey(db, storeName,taskId).then(res=>{
         //console.log('离线数据123',JSON.stringify(res))
         let data=res
         data['isOver'] = false
         if(data.workTicket && data.workTicket.endTime && new Date().getTime() > new Date(data.workTicket.endTime).getTime()) {
           data.isOver = true //工作票超时
         }
         
         vm.projectList = data
         
         console.log('工序', Object.values(vm.projectList.wpItemList))
         // 统计工序个数
         let arr = []
         Object.values(vm.projectList.wpItemList).forEach((a, i) => {
           arr.push(a.taskWps.length)
           a.childs.forEach((b, index) => {
             arr.push(b.taskWps.length)
             b.childs.forEach((c, index) => {
               arr.push(c.taskWps.length)
             })
           })
         })
         vm.countWp = arr.reduce((x, y) => x + y)
       })
           
      }
      // 离线数据缓存
      function offlineData(projectTaskId){
        mui.baseApp.httpRequst(
          "get",
          "/app/api/project/execution/offline/data/"+projectTaskId,
          {},
          function (data) {
            data.data['isOver']= false
            data.data['id'] = projectTaskId
            console.log('离线数据11',data)
            let datas=data.data
            // deleteDB('myDB', 'db_2', 1)
             // getLineAdd(datas)
             getSearchData(datas)
             // getLineAdd(datas)
          },
          function () {
            plus.nativeUI.closeWaiting()
            console.log("获取数据失败")
          }
        )
      }
     function getSearchData(data){
       //通过游标
       cursorGetData(db, storeName).then(res=>{
         console.log('333',res)
         if(res.length>0){
          let arr= res.find(msg=>{
              console.log('3331',msg.id)
              return data.id==msg.id
           })
           console.log('333获取缓存',arr)
           if(arr){
             getUpData(data)
           }else{
             getLineAdd(data)
           }
           console.log('333100',arr)
         }else{
           // getUpData(data)
           getLineAdd(data)
         }
          
         // console.log('id对比',data.taskInfo.id,res.taskInfo.id)
          
       //通过id读取数据
        // getDataByKey(db, storeName, id).then(res=>{
        //   console.log('333',res)
        //   // return res
        // }).catch(function (error) {
        //  console.log(error);
        // })
         
          // return res
        }).catch(function (error) {
         console.log(error);
        })
      }
     function getLineAdd(data){
        console.log('add',data)
        addData(db, storeName, data).then(res=>{
          console.log('add数据',res)
          // return res
        })
      }
      function getUpData(data){
        updateDB(db, storeName, data)
      }
      function getDel(id){
		    localStorage.removeItem(id)
        deleteDB(db, storeName, id)
      }
     function getSysInfo() {
		//return false

		types = {};
		types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
		types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
		types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
		types[plus.networkinfo.CONNECTION_WIFI] = "WiFi网络";
		types[plus.networkinfo.CONNECTION_CELL2G] = "2G蜂窝网络";
		types[plus.networkinfo.CONNECTION_CELL3G] = "3G蜂窝网络";
		types[plus.networkinfo.CONNECTION_CELL4G] = "4G蜂窝网络";

		var str = types[plus.networkinfo.getCurrentType()];
		if (str == '未知' || str == '未连接网络') {
		  return false;
		} else {
		  return true;
		}
       
      }
      window.addEventListener('back', function(event) {
        let data = event.detail
        if(lineType){
			if(vm.isOnlineAndOfflineData){
				getLineData()
			}else{
				console.log('在线')
				//vm.allSub(false)
				getProject()
				// offlineData(taskId)
			}
        }else{
          getLineData()
        }
      })
    </script>
  </body>
</html>
